Skip to content

NXstress writes the calibration file's detector chain (#1099) - #1132

Open
fanchercm wants to merge 12 commits into
nextfrom
feature/1099-nxstress-chain
Open

fanchercm wants to merge 12 commits into
nextfrom
feature/1099-nxstress-chain

Conversation

@fanchercm

@fanchercm fanchercm commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

What

NXstress now writes the detector chain the calibration file uses, so external NeXus tools place the pixels where PyRS reduction does (#1099, the last phase of #1054).

  • Shared chain: calibration_nexus.detector_transformations writes it for both files: shift_x, shift_y, rotation_z, rotation_y, rotation_x, arm_length, shift_z, two_theta_0 (about Y), arm_rotation. The detector's depends_on is transformations/shift_x.
  • Arm angle: arm_rotation holds one value per scan point, −(the 2theta log). It grows on append and is NaN without a 2theta log.
  • Arm length: a single value, from the L2 log when there is one, else the instrument's. An entry whose L2 differs between scan points is refused.
  • Errors: each calibration parameter has a <name>_errors value; −1 where the error is unknown. Errors survive reading an entry back and writing it again.
  • Applied calibration recorded on load: a workspace loaded from a project file keeps the calibration its reduction recorded (get_recorded_calibration()), and NXstress writes that.
    • Before this, NXstress written from reduced data always described the uncalibrated detector.
    • It is kept separate from get_detector_shift(), so re-reducing a project file without a calibration file still uses the uncalibrated geometry, as before.
    • Appending a file reduced with a different calibration (or none) clears it, with a warning.
  • Old files are read only: instrumentFromNexus reads the new names first, then the old ones. A refused append to an entry written before NeXus calibration phase 4: NXstress output uses the calibration file's transformation chain #1099 says so in its message.

Tests

  • Unit tests for the chain's names, order and axes, errors, append, the L2 refusal, the old layout, and the recorded calibration on load and append.
  • Integration tests:
    • test_nxstress_calibration.py (new): reduces HB2B_3510 with the ring reference calibration and checks that the written chain places the real pixels where lab_positions does, with that calibration's values and errors.
    • The real sample-position fixture now also checks the arm angle, the arm length and the error set.
  • Results: the unit tier passes (1321), as do the NXstress, workspace and calibration integration tests and pixi run mypy pyrs scripts tests.

Reviews

  • The code review and test review ran on the first two commits; their findings are fixed in commits 2 and 3.
  • The last commit (the test-review items, the refusal message and DD-34, first committed as DD-30) has not been reviewed separately.

Deferred

DD-34: a project file that reduction writes to a new path has no instrument geometry, so NXstress can't be written from it. This affects Manual Reduction's output. The problem predates this PR and is recorded in docs/deferred_defects.md.

Refs #1099, #1054

🤖 Generated with Claude Code

fanchercm and others added 3 commits November 20, 2026 09:52
NXstress's detector chain did not place pixels as reduction does: entered
at the innermost transformation (NeXus) it applied 2theta_0 first and the
shifts last, about X, with no arm angle. Nothing in PyRS read it (reduction
unaffected); external NeXus tools were misled. Design approved on #1099.

- calibration_nexus.detector_transformations: the calibration file's chain
  writer, now shared; NXstress writes shift_x ... two_theta_0 (about Y),
  arm_rotation, each calibration parameter with <name>_errors.
- arm_rotation per scan point, -(2theta log), growable on append; NaN
  without a 2theta log.
- One arm_length: the runs' L2 log when present (what reduction uses), else
  the instrument's; an L2 that differs between scan points is refused.
- Errors from the applied calibration, -1 where unknown.
- A workspace loaded from a project file keeps the calibration reduction
  applied (get_recorded_calibration, from the file's record), so NXstress
  from reduced data now writes the calibrated detector instead of the
  nominal one. Kept apart from get_detector_shift: reduction applies that
  when no calibration file is given.
- instrumentFromNexus reads the new names first, then the old ones.
- Tests: the chain applied without DetectorModel reproduces lab_positions
  at every scan point; recorded calibration and errors; unknown errors -1;
  differing L2 refused; missing arm angle NaN; old layout read; workspace
  loading keeps the record apart. Recorded in ground_truths.

Refs #1099, #1054

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… calibration

- Reading NXstress back dropped the calibration's <name>_errors, so writing
  it again (e.g. after refitting peaks) wrote -1 for every parameter.
  instrumentFromNexus's companion shiftErrorFromNexus reads them, the
  read-back workspace keeps them (set_recorded_calibration), and the writer
  uses them when the recorded calibration is the workspace's shift.
- A workspace built from several project files (append_hidra_project) kept
  the first file's recorded calibration, so NXstress labelled every scan
  point with it. The appended file's record must match, or the combined
  data records none (with a terminal warning).

Refs #1099

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ies, DD-30

- T1: real-data test (HB2B_3510 reduced with the ring reference calibration) that the
  NXstress chain carries the applied calibration, its errors, arm angle and arm length,
  and places the real pixels where lab_positions does.
- T2-T7, T10: per-parameter errors, unknown errors, own shift vs another record, L2
  refusal, missing arm angle, old layout read-back, AAA structure.
- T3: appended arm angles, appending to a pre-#1099 entry, differing L2 refused.
- T8: arm angle and arm length checked on the real sample-position fixture.
- T9: a record of no calibration, and an unreadable record (warned, data still load).
- C1: refusing an append to a pre-#1099 entry now says why.
- DD-30: reduction to a new file writes no instrument geometry (deferred).

Refs #1099, #1054

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

…-chain

# Conflicts:
#	docs/deferred_defects.md
@fanchercm
fanchercm requested a review from ekapadi November 20, 2026 19:39

@ekapadi ekapadi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR review — #1132 (feature/1099-nxstress-chain)

This is the review of PR #1132: next..feature/1099-nxstress-chain, based on next
at 9fd090e2. With it, NXstress writes the calibration file's detector chain, including the per-scan-point
arm angle and the calibration's errors.

#1132 overlaps the planned NXstress implementation work that connects the NXstress backend to PyRS core. Its
parts are named here by number and slug. Two matter most:

  • the phase-3 PR (EWM17019_NXstress_hookup_phase_3): the 05 strain-stress-viewer subspec for the NXstress
    hookup, with the same base as #1132;
  • the 04d extended-two-theta subspec for the NXstress hookup (diffractogram identity, eta wedges and
    two-theta axes), which follows phase 3.

This review first settles how #1132 fits with both. The reviewer's specific questions, and then a general
review, follow below.

Summary notes:

  • The conflicts with my 'phase-3' PR are quite minor, so we don't need to be too concerned with that!

  • Several of the review comments below were triggered by rules in my own CLAUDE.local.md, which is fairly complex.
    There are several of these rules that I'm recommending we promote into the repository's CLAUDE.md.

Recommended coding rules to move to CLAUDE.md

Several findings below rest on rules that are, today, only in the reviewer's private CLAUDE.local.md, plus
one new rule this review proposes. #1132's author does not have that file, so the PR cannot be held to them
as written. The reviewer intends to move them into CLAUDE.md, so that they become project rules (CLAUDE.md
names .github/copilot-instructions.md as its mirror, but that file does not exist yet); that decision is
not yet approved
. Until it is, findings that rest on these rules are recommendations to #1132's author, not
requirements, and each one points back here with "(see Recommended coding rules, above)".

Each rule below lists the findings it drives, then the exact text to add to CLAUDE.md, ready to paste.
The first four are copied verbatim from CLAUDE.local.md; the fifth is new. They would sit together after
CLAUDE.md's Code Quality Standards, as top-level ## sections, as they do in CLAUDE.local.md.

1. None must name a value, not a gap

This is a general rule, which has evolved over time. It was primarily triggered by the observation that
many developers reflexively set the default values of parameters to None, and then this default value
serves as a sentinal conflating both cases: (i) the parameter is unset, and (ii) the parameter has its default value.
In most cases, an unset parameter should trigger an error, and under this common usage, this case can no longer be detected!

  • R2, G1: None as the applied calibration means the nominal detector, and nothing else; the full policy
    is in R2, under The None policy.
  • R2, G2: an unknown calibration, including one merged from different calibrations, gets its own literal
    value (CalibrationSource.UNKNOWN, rule 5), not None.
  • G7: the shift_error=None default on set_recorded_calibration (one filler, so no default).
  • Related: phase 3 adds pyrs.utilities.unset.Unset for "not supplied"; it is not on next yet.
## `None` must name a value, not a gap

**Absence must be distinguishable from a falsey value.** `""`, `[]`, `0` and
`None` each mean something real somewhere, so none of them can also mean "not
supplied". `arg: Optional[T] = None` is where that collapse usually enters: the
default makes "the caller decided `None`" and "the caller passed nothing" the same
observation, and nothing at the call site recovers the difference. An argument
whose absence would be a wiring bug therefore carries **no default at all** —
required and keyword-only. `None` is then free to mean what it says.

Two corollaries:

- `None` must name a value in the argument's **domain**, never a gap. A `None`
  standing in for "not computed yet" makes a half-built object indistinguishable
  from a finished one; whatever the consumer actually wanted — usually an empty
  collection — was the right value all along.
- **Count the fillers.** One filler means absence is a bug, so no default. When
  two parties fill a field — a model plus a prep hook, or a writer plus a reader
  deserialising stored rows — absence from *one* of them is the normal case, so
  the default is correct and the guard moves to whichever filler can tell that it
  failed. (A row written by an *older version* of the code is not a filler: that is
  a migration, done with the change, not an ongoing absence to guard against.)
  For example:

```python
class ReductionRequest(BaseModel):
    calibration_file: Optional[str] = None  # the caller never supplies this; a later step fills it


def prepare(request: ReductionRequest) -> None:
    ...
    raise RuntimeError("calibration_file could not be resolved")  # never a quiet return
```

Why: requiring a field that a *second* party fills publishes it to the first one, which
may have no way to supply it correctly. And a guard needs the information to be right: a
step that sees only the payload cannot tell "this field does not exist here" from "this
field was lost", so that check belongs in a test that reads the schema instead.

2. Keyword-only arguments

This rule was triggered by the observation that in larger codebases, as the functionality is extended,
many API functions gradually accumulate more and more parameters. Many silent defects are caused
by mis-ordering positional parameters. Use of proper type annotation can help with this issue, but
in reality, it's somewhat in conflict with Python's design [and strength] as a programming language.

Under an object-oriented programming paradigm, we [at least attempt to] use object scope to limit the size of these parameter sets, but
this cannot always be done successfully. A work-around, which fixes many silent defects, is to simply specify
all parameters using their names in production code. This rule applies this approach, strictly limiting the number of
positional parameters, and then assigning keyword names to the bulk of the rest of the parameters.

  • G7: detector_transformations(shifts, shifts_error, arm_length, arm_rotation=None), called by position.
## Keyword-only arguments

Any function or method with more than 3 arguments, or with any argument
that has a default value, keeps only its first one or two "primary
subject" arguments positional — every other argument, whether it has a
default or is required, goes after a bare `*`. This applies even to
required arguments once the threshold is crossed, so that a function's
argument list can grow later without breaking a positional call site.

```python
def reduce_sub_run(
    run_number: int,
    *,
    detector_name: str,
    calibration_file: str,
    sub_runs: list[int],
    output_path: str,
): ...
```

Why: adopted as a general convention rather than from a specific PyRS incident — no
function here has yet crossed the 3-arg/any-default threshold with a positional
signature, so there is no local call-site cost to cite either way. Keeping required
arguments positional past that threshold is what causes silent breakage later — a
caller relying on positional order has no warning when a new required argument is
inserted in the middle. Apply this when writing or extending a function that crosses
the threshold, not as a retroactive sweep of existing ones.

3. Import placement

  • G7: unjustified function-local imports in two tests and the _calibrated_instrument helper.
## Import placement

**All imports go at the top of the file.** A function-local (deferred)
import is allowed only when a top-level import would actually break — and
when it is, the reason goes in a comment on the import line or immediately
above it, naming the specific cycle or condition:

```python
def get_handle(self, name: str):
    from other_module import Handle  # deferred: other_module imports this module

    ...
```

The three cases that genuinely justify deferring, and nothing else:

1. **A real circular import.** Name the other module and the direction, as
   above. "Might be circular" is not a justification — if you have not seen
   the `ImportError`, move it to the top.
2. **An optional dependency** not installed in every environment
   (`nltk`, `sounddevice`, ...). Say which environment lacks it.
3. **A genuinely expensive module-load** deferred off a hot import path, with
   a note on what it costs.

Do **not** defer an import to make `unittest.mock.patch` work. `from x import
f` at module level binds `f` at import time, so patching `x.f` does not reach
it — but the fix is to import the *module* at the top and call through it,
which stays patchable:

```python
import some_module  # top-level


def get_resource():
    return some_module.get_settings().resource_root
```

Why: a deferred import hides a module's real dependency graph, moves
`ImportError`s from startup to whenever that branch first runs, and costs a
`sys.modules` lookup on every call. PyRS already has instances of the shape this
rule targets — `pyrs/utilities/NXstress/_peaks.py`'s `from ._fit import
_PeakParameters, _BackgroundParameters` and `from ._definitions import
GROUP_NAME, UNDEFINED_PEAK_TAG`, both inside a method body with no comment
justifying the deferral. This rule applies to code you touch; existing
instances are not to be swept up unless asked.

4. Private names do not cross module boundaries

  • G7: test_nxstress_calibration.py imports _chain_matrix from test_instrument.py. The test exception
    covers a test importing a private from the module it tests, not from another test module.
## Private names do not cross module boundaries

A leading underscore means *this module owns this name*. Another module
importing it is a contradiction in terms, and it is always a signal about
placement rather than a shortcut worth taking:

```python
from some_package.internals import PublicThing, _private_helper  # do NOT do this
```

Two sanctioned fixes, and which one applies is a question about ownership:

1. **The name is genuinely part of that module's contract** and was
   underscore-prefixed by habit. Drop the underscore, so the module exports it
   deliberately.
2. **Two modules both need it and neither owns it.** Extract it to a leaf
   module they both import. This is the case whenever the import also closes an
   import cycle — the cycle is the evidence that the name is in the wrong place.

Two things this does **not** forbid:

- `import public_name as _alias`, which is the opposite move: taking a public
  name and keeping it out of the importing module's own surface. The rule is
  about the name at its *definition*, not at the call site.
- A **test** importing a private from the module it is testing —
  `tests/unit/pyrs/utilities/NXstress/test_peaks_read.py` reaching directly for
  `_peaks._Peaks` and `_fit._PeakParameters`. That is ordinary white-box
  testing, and the test breaking on a rename is the intended behaviour rather
  than collateral damage.
- A package's own orchestrating module assembling its public surface from its
  sibling private modules — `pyrs/utilities/NXstress/NXstress.py` importing
  `_Instrument`/`_Sample`/`_Fit`/`_Peaks` from `_instrument.py`/`_sample.py`/
  `_fit.py`/`_peaks.py`. These are the package's own internals talking to each
  other, not one package reaching into another's; see *Private modules are not
  the same thing as private names* below.

Why: a private name carries no stability contract, so renaming one inside its
owning module is an unannounced breaking change to code its author never looked
at — and the underscore is precisely what told that author they were free to
rename it. This rule applies to code you touch; existing violations are not to
be swept up unless asked.

### Private modules are not the same thing as private names

`pyrs/utilities/NXstress/` is built from underscore-prefixed *files* —
`_peaks.py`, `_fit.py`, `_definitions.py`, `_sample.py`, `_instrument.py`,
`_discriminator.py`, `_input_data.py`, `_runs.py`, `_workspace_key.py`,
`_validation.py`, `_append.py`, `_read.py` — each an implementation detail of the
`NXstress` package as a whole, not of any one file inside it. That is a
**layout** choice, answered by *where a file sits*, and this rule does not
touch it: `NXstress.py` importing `_Peaks` from `_peaks.py` is the package
assembling its own public surface, the same as the test exception above.

The rule is violated when a module **outside** `pyrs/utilities/NXstress/`
imports one of these names directly — `pyrs.core` reaching for
`pyrs.utilities.NXstress._peaks._Peaks` instead of whatever `NXstress`
re-exports publicly. The leading underscore on a *module* still means
something; it just answers a narrower question — "is this file part of the
package's own internals" — than the leading underscore on a *name* crossing a
boundary the package did not draw.

5. Named states are literals, not free text

  • R2: the calibration's source becomes CalibrationSource, and a merge records CalibrationSource.UNKNOWN.
  • G2, G3, G9: every "calibration unknown" case uses that one member, and NXstress writes it as its marker.
  • G7: the AppliedCalibration record carries a CalibrationSource.
## Named states are literals, not free text

**A value that names one of a fixed set of states is defined once, as a str-valued
`Enum` (or a `Literal` type), and every module that writes, reads or compares it
imports that one definition.** A state spelled out as a bare string at each use
(`"none"`, `"file"`, `"unknown"`, ...) lets a typo silently become a new state that
no reader handles, and leaves no single place that lists the states there are.

```python
class CalibrationSource(str, Enum):
    NONE = "none"            # nominal detector: no calibration applied
    FILE = "file"            # a calibration file
    WORKSPACE = "workspace"  # the workspace's own shift
    UNKNOWN = "unknown"      # a calibration was applied, but which one cannot be stated
```

- **Keep the stored strings as the members' values**, so files already written read
  back unchanged and no migration is needed.
- **A stored string that is not a member is read as an explicit fallback member**
  (usually `UNKNOWN`), with a warning: never passed through as a new state, and
  never turned into `None`.
- This pairs with *`None` must name a value, not a gap*: "unknown", "mixed" or
  "lost" are states of their own and get members of their own, rather than
  borrowing `None`.

Why: the review of PR #1132 found the calibration's source written as free text in
several modules: `"none"`/`"file"`/`"workspace"` in `HidraSetup`, `"unknown"` in the
project-file writer, and `record.get("source", "none")` defaults in the readers.
Nothing ties these together, so a misspelling in any one of them is a new,
unhandled state rather than an error. This rule applies to code you touch; existing
instances are not to be swept up unless asked.

The review practice also follows one CLAUDE.local.md rule that is about process, not code: probe before
asserting
(Auditing a Plan or Subspec). A claim about how another module treats our output is backed by a
probe: a short script driving the real code, run before the claim is made. R3's check of the detector
shift is one. It is part of a more comprehensive plan-audit
process as a whole, so it is not proposed for CLAUDE.md here.


R1 — Merge order: #1132 may merge before phase 3 (decision)

Concern: #1132's NXstress changes might clash with phase 3's combined (run_number, scan_point)
index, or with the planned 04d work. If so, they would have to wait for both PRs.

Resolution: they do not clash. #1132 may merge first, and phase 3 is then rebased onto it. This is
the order we propose.

Evidence:

  • A trial merge touches no worktree or ref:
    git merge-tree --write-tree --name-only origin/EWM17019_NXstress_hookup_phase_3 upstream/feature/1099-nxstress-chain.
    It conflicts in four files only:

    • docs/deferred_defects.md and docs/ground_truths.md: the conflict is only where both sides add at the
      end. The DD numbers are distinct: phase 3 adds DD-6 to DD-9 and DD-32, #1132 adds DD-34.
    • tests/unit/pyrs/utilities/NXstress/test_append.py: both sides add classes at the end (phase 3:
      TestRunIndexOnAppend, TestAFailureWhileComputingWritesNothing; #1132: TestDetectorChainOnAppend).
    • pyrs/utilities/NXstress/NXstress.py: #1132 adds two lines to the old reader's _workspaceFromNexus,
      which phase 3 replaced with _read.py.

    _instrument.py, workspaces.py and test_workspaces.py merge without conflict.

  • The (run, scan_point) index is unaffected. The one new per-scan-point dataset is
    DETECTOR/transformations/arm_rotation (_Instrument._concatenated_arm_rotation).

    • It is built positionally, in workspace order over ws.get_sub_runs(). Phase 3 builds every other
      column in the scan-point family the same way: monochromator/wavelength, SAMPLE_DESCRIPTION/scan_point
      and run_number. So its rows line up with the index with no further work.
    • It is created with growable(1), grows through tail_append, and is listed in
      _Instrument.appendableDatasets. So phase 3's compute-then-write append (deferred_appends) and its
      shape check (_append.validate_appendable_shapes) cover it unchanged.
    • The reader never slices it by rows: the arm angle comes back through the 2theta sample log. So
      phase 3's split of an entry into its workspaces is unaffected.
  • 04d works in FIT/peaks, on the two-theta axes and in the reduction call. It does not touch the
    detector chain; in the instrument group it changes only the mask-name encoding under instrument/masks.
    It shares workspaces.py and _instrument.py (and the tests test_workspaces.py and test_append.py)
    with #1132, in different code.

R2 — One NXstress entry holds one calibration (working answer)

Question: should an NXstress entry be able to combine runs reduced with different calibrations? Phase
3 writes several runs into one entry; the strain/stress viewer's three directions are the ordinary case.
With #1132, _Instrument._entry_wide_geometry refuses runs whose applied calibrations or L2 differ
(_applied_shift, _effective_geometry).

Working answer: keep the refusal. Settle which calibration to use before saving as NXstress.

A mixed entry is technically feasible, for example by storing the calibration per scan point, behind a
Config flag. We decline it: that much flexibility mostly lets users make mistakes.

Merging in PyRS core is accepted, and records the calibration as unknown.

  • HidraWorkspace.append_hidra_project (CombineRuns, and the peak-fitting multi-file load) merges runs
    whose recorded calibrations differ, and warns. That stays: the rule's scope is that the NXstress backend
    never merges calibrations
    ; a merge in PyRS core is the user's explicit choice.
  • What changes is the value the merge records. Today it sets the record to None. It should record the
    calibration as unknown, using the literal CalibrationSource.UNKNOWN below, with the reason ("merged
    from runs reduced with different calibrations"). NXstress then writes the "calibration unknown" marker (G2),
    not the nominal chain.

The None policy for the applied calibration (the None rule; see Recommended coding rules, above).
None names exactly one value in the calibration's domain: the nominal detector — reduction applied no
calibration
. It never stands for "not known", "lost" or "mixed". Each of those is a fact about the data
that the record must keep, so each gets its own explicit value.

Why this is better than None for a merge:

  1. None is a claim, not a gap. NXstress turns None into calibrated=False and the nominal chain: a
    statement that the data were reduced with the uncalibrated detector. After a merge of calibrated runs
    that statement is false, and nothing in the file says so.
  2. It stays distinguishable. With None for both, a merged workspace and one that was never calibrated
    look the same, as this section originally accepted. With an explicit value they do not, at no cost.
  3. It reuses one state instead of adding cases. G2 already needs "unknown" for a record the file says
    could not be written, or that could not be read. A merge is the same situation (a calibration was applied,
    and which one cannot be stated), so the merge, G2's cases, G3's differing-errors merge and G9's missing
    calibration field all land in one state, which NXstress writes one way.

Literal, not free text. Today the calibration's source is free-form text spread over several modules:
"none", "file", "workspace" in HidraSetup, "unknown" in the project-file writer
(file_object.py), and record.get("source", "none") defaults in the readers. A typo in any of them
silently becomes a new state. The suggestion is one str-valued enum, defined once and imported by every
module that writes or reads the record (HidraSetup, HidraProjectFile, HidraWorkspace, NXstress):

class CalibrationSource(str, Enum):
    NONE = "none"            # nominal detector: no calibration applied
    FILE = "file"            # a calibration file
    WORKSPACE = "workspace"  # the workspace's own shift
    UNKNOWN = "unknown"      # a calibration was applied, but which one cannot be stated
  • The stored strings are the ones already written, so existing project files read back unchanged.
  • An unrecognised string in a file is itself read as UNKNOWN, with a warning, never as a new state.
  • In memory, the record (G7's AppliedCalibration) carries a CalibrationSource, and NXstress writes the
    same literal as its marker, so both file formats use one vocabulary.
  • CalibrationSource.NONE exists only as the stored string. A record stored with source "none" reads back as
    the None record, and an AppliedCalibration never carries NONE, so "nominal detector" has exactly one
    in-memory form.

Project files with no record at all are UNKNOWN too (recommended). Since #1053 every reduction
writes a record, with source "none" when no calibration was applied. A file with no record was therefore
reduced before #1053, with a calibration that cannot be known. Today it loads as None, and NXstress writes it
as uncalibrated (_load_recorded_calibration: "A file with no record (reduced before #1053, or never
calibrated) keeps None"). That is the same false claim as point 1 above. We recommend that such a file load as
CalibrationSource.UNKNOWN, with the reason "no calibration record (reduced before #1053)". The visible effect
is that NXstress writes the "calibration unknown" marker instead of calibrated=False for every pre-#1053
project file. That is the honest statement about those files, and it needs no migration: the file is not
changed, only what is said about it.

R3 — Can a detector shift be applied to the arm more than once?

Question (reviewer): in earlier PyRS it was possible to apply several calibrations to the arm by
accident, because nothing recorded whether a detector shift had already been applied. Does #1132 fix this?

Resolution: in practice, yes. Reduction could already apply a shift only once, through #1011 and #1053.
#1132 fixes the NXstress side and adds a record of the calibration that was applied. The root cause is
still in the code, though: the geometry still keeps no record of being calibrated, and the in-place shift
method is still there. We suggest #1132 record it as DD-35 (text below).

  • Reduction (before #1132):
    • Reduction builds the pixel positions afresh from the uncalibrated geometry every time
      (ResidualStressInstrument.build_instrument → DetectorModel.lab_positions). It never writes the shift
      back into the geometry.
    • A calibration file replaces the workspace's shift; the two are never added (ReductionApp
      passes the file's DENEXDetectorShift itself to reduce_diffraction_data).
  • #1132:
    • The old NXstress writer wrote distance = geom.arm_length, with a TODO saying it could not tell whether
      the shift had already been folded in. #1132 writes the arm length from the uncalibrated geometry or the
      L2 log, and writes shift_z as a step of its own in the chain.
    • HidraWorkspace now separates the shift a future reduction will apply (get_detector_shift) from the
      one that was applied (get_recorded_calibration, from the project file's reduction record). NXstress
      writes the recorded one only when the workspace has no shift of its own; otherwise it writes the shift
      (G1).
    • The NXstress reader sets both. Reducing a read-back workspace again re-applies the same shift to the
      uncalibrated positions; it does not stack a second one on top.
  • Still in the code (the suggested DD-35; it predates #1132, and no fix is asked of it):
    • DENEXDetectorGeometry.__init__ takes calibrated and discards it. #1132's new _effective_geometry
      passes False, and the NXstress reader (already before #1132) passes the file's flag; both values are
      thrown away.
    • DENEXDetectorGeometry.apply_shift adds shift_z to the arm length in place. It is reached only
      through HidraSetup.get_instrument_geometry(True), which nothing calls. It also raises AttributeError
      before changing anything.
    • Suggested fix: store the flag, and make apply_shift refuse an already-calibrated geometry (or remove
      the in-place path).

We probed this on feature/1099-nxstress-chain, driving PyRS's real code. It showed that:

  1. building the instrument twice with the same shift gives identical pixel positions, and leaves the
    geometry's arm length unchanged (2.0 m before and after);
  2. after a calibration file is loaded, the shift reduction will apply is the file's (shift_z = −0.0201), not
    the workspace's (0.03): the file's replaces it;
  3. two NXstress write → read round trips keep the arm length (2.0) and shift_z (0.03) apart and unchanged;
  4. HidraSetup.get_instrument_geometry(True) raises AttributeError (DENEXDetectorShift has no attribute
    calibration_file) on every call, and the arm length stays 2.0;
  5. a DENEXDetectorGeometry built with calibrated=True keeps no attribute holding the flag.

Check 2 is at the HidraSetup.load_calibration_file level, as ReductionApp uses it. It is not
a full reduction.

Suggestion for #1132: add DD-35 to docs/deferred_defects.md. The defect is not caused by this PR. It
is related to it, though: #1132 adds a new place that passes the discarded calibrated flag
(_Instrument._effective_geometry; the reader, instrumentFromNexus, already did), and it removes the
NXstress TODO that pointed at the same gap. Recording it in this PR keeps that trail. The number 35 is free on next,
on #1132 and on phase 3. Suggested text:

- **DD-35**, 2026-11-21: `DENEXDetectorGeometry` takes a `calibrated` flag and discards it. Nothing then
  records whether a detector shift has been applied to a geometry, and the one method that shifts a geometry in
  place is broken.
  - **Cause:** `DENEXDetectorGeometry.__init__` (`pyrs/core/instrument_geometry.py`) checks `calibrated` and
    never stores it. `DENEXDetectorGeometry.apply_shift` adds `shift_z` to `_arm_length` in place, so a second
    call would shift the arm again. It is reached only through `HidraSetup.get_instrument_geometry(True)`,
    whose TODO lists the same three problems: it returns None, it could apply the shift repeatedly, and it
    changes the uncalibrated geometry.
  - **Today:** nothing calls `get_instrument_geometry(True)`. Reduction applies the shift to freshly computed
    pixel positions (`DetectorModel.lab_positions`) and never changes the geometry. `apply_shift` raises
    `AttributeError` before it changes anything: it reads `DENEXDetectorShift.calibration_file` from the class,
    which has no such attribute. Every caller of the constructor, including NXstress, passes a flag that is
    then thrown away.
  - **Fix:** store the flag and expose it. Have `apply_shift` refuse a geometry that is already calibrated,
    and either return the shifted geometry or remove `apply_shift` and `get_instrument_geometry(True)`
    entirely.

  **Found during:** the review of #1132 (#1099).
  **Why it is deferred.** It predates #1099 and is in instrument geometry, which is scientific production code.

R4 — General review

Six review agents read git diff 9fd090e2...19dd2525, with R1–R3 excluded, each for one aspect: code, tests,
comments, error handling, type design and simplification. Every finding was checked against the code before
being kept. Where several agents found the same thing, it is listed once below, as G1–G9; a finding with two
parts is cited under both.

What was checked and found sound:

  • pixi run mypy pyrs scripts tests → Success: no issues found in 282 source files.
  • The touched unit tests: 120 passed, 2 xfailed.
  • No agent found a logic error in the scientific behaviour:
    • the chain's order and axes match DetectorModel.lab_positions, i.e. reduction (whether reduction itself
      is right is R5);
    • arm_rotation = −(2theta log);
    • L2 matches what reduction uses;
    • no correction parameter is added.

G1 — The applied calibration: where it is held, how it is identified, and who records it — valid, important

Comment (agents): ReductionApp.reduce_data never sets _recorded_calibration. A workspace reduced in
the session therefore has no record, or keeps a stale one from its project file. And _Instrument._applied_shift
prefers get_detector_shift() (the shift the next reduction will apply) over the record, so a shift set by
FitCalibration but not yet used to reduce would be written as applied.

Reviewer: these are three separate issues, and the third is the point of G1.

  1. The calibration is held in more than one place, and they can disagree.
  2. A calibration has no identity. It should probably be identified by a hash key, and that key stored.
  3. Reduction does not record the calibration it applies. Applying a calibration is what reduction is
    for, so it makes no sense that reduction is not the party that sets this one field.

Resolution: valid, all three. Latent today: no viewer that saves NXstress reduces data in the session
(they load project or NXstress files). It will bite the 07
manual-reduction-nxstress subspec for the NXstress hookup
, where Manual Reduction writes NXstress from a
workspace reduced in the session.

1. Several holders. Calibration state is held in three places, none derived from the others:

Holder Holds Set by
HidraWorkspace._instrument_geometry_shift (get_detector_shift) the shift the next reduction will use callers, FitCalibration, NXstress read-back
HidraWorkspace._recorded_calibration (shift, shift_error) said to be applied project-file load/append (_read_recorded_calibration), NXstress read-back (set_recorded_calibration)
ReductionApp._instrument (HidraSetup.calibration_record()) the full record: values, errors, file, calibration_file_sha256, source, provenance load_calibration_file or use_workspace_calibration, in reduce_data

_applied_shift reconciles the first two by guessing: shift first, and the record's errors only if the record has
the same values. The third, the only complete one, goes to the project file at
save_diffraction_data → write_reduction_provenance and never reaches the workspace.

2. No identity. Two calibrations are "the same" if their seven shift values are equal, and this rule is coded
twice: workspaces._shift_values (for append_hidra_project) and _Instrument._shift_key (for the NXstress
refusal). Neither includes the wavelength, which the calibration also sets. A calibration_file_sha256 exists,
but it is a hash of the file, it is kept only in the project file's record, and _read_recorded_calibration
drops it when loading: the workspace keeps only (shift, shift_error). A calibration from FitCalibration in
the session has no file and so no hash at all.

3. Reduction does not record what it applies. reduce_data applies the calibration and save_diffraction_data
writes its full record to the project file, but neither sets it on the workspace. So the only way a workspace
learns what was applied to its own data is by being saved and loaded again.

Suggested Fix:

  • One field, set by one party. The workspace holds a single record of the applied calibration. Reduction
    sets it, every time, to what it applied (None for the nominal detector). Loading a project file or reading
    NXstress back restores it. get_detector_shift() stays as the request for the next reduction and is never
    read as "applied"; _applied_shift's fallback goes.
    • This builds on the author's own reasoning, not against it. #1132's ground truth ("NXstress detector chain
      is the calibration file's") keeps the record apart from get_detector_shift() on purpose: setting the
      shift on load would make reducing a project file again, without a calibration file, silently switch from
      the nominal geometry to the recorded one. The suggestion keeps that separation, and adds only that
      reduction, not just loading, sets the record.
  • Identify a calibration by a hash key computed from its content: the canonical calibration values
    (shift, 2θ₀, wavelength) and their errors. The same calibration then has the same key whether it came from
    a JSON file, a NeXus file or FitCalibration in the session. The file's sha256 stays as provenance. The key is
    stored with the record in the project file and in NXstress, and _shift_values/_shift_key become one key
    comparison. How a record whose errors are lost is keyed depends on G3's open question.
  • These change production behaviour, so the timing is the PR author's call: in #1132, or as a tracked
    follow-up that must land before that 07 work.

Rebutted part: one agent's claim that "a read-back workspace that is reduced again applies the
calibration a second time" is wrong. The shift is re-applied to the nominal positions, not stacked, as R3's
probe showed.

Evidence:

  • grep -rn "_recorded_calibration\s*=\|set_recorded_calibration" pyrs → workspaces.py (init, load, append)
    and NXstress.py (read-back) only; nothing in powder_pattern.py.
  • powder_pattern.py: save_diffraction_data calls out_file.write_reduction_provenance(instrument=self._instrument, ...);
    reduce_data writes nothing back to the workspace except the wavelength.
  • instrument_geometry.py: HidraSetup.calibration_record() includes calibration_file_sha256, set from
    _file_sha256(calibration_file) in load_calibration_file.
  • workspaces.py: _read_recorded_calibration returns instrument.geometry_shift, instrument.geometry_shift_error
    only.

G2 — An unknown record is written as "uncalibrated" — valid, important

Comment (agent): _read_recorded_calibration returns None, the same value as "never calibrated", in three
cases:

  • (a) the project file says the record could not be written: {"source": "unknown", "error": ...}, from
    file_object.py. The record has no calibration key, so the reader returns None. This is silent.
  • (b) a source other than "none" with no calibration key. This is silent.
  • (c) any exception, including programming errors, caught by except Exception and logged as a warning.

NXstress then writes the nominal chain with calibrated=False. "Unknown" becomes a positive claim that no
calibration was applied.

Reviewer: "unknown calibration" is probably a state we should support. This is the None rule (see
Recommended coding rules, above): None is a value in the calibration's domain, the nominal detector, so
it cannot also mean "we do not know". An unknown calibration is set to its own, explicit value rather than
passed as None.

Resolution: valid. It is the same state R2 gives a merge of different calibrations: a calibration was
applied and cannot be stated. Here the file even says the record is unknown, and the reader throws that away.

Suggested Fix:

  1. Support "unknown" as a state of the applied-calibration record (G1's single field), distinct from None
    (nominal) and from any record with a content key: a record whose source is the literal
    CalibrationSource.UNKNOWN (R2), carrying the recorded reason (the record's error text) and no content key. The project file already writes
    that string.
    • It is not Unset (phase 3, "the caller did not supply this"): the record was supplied, and says
      the calibration is unknown.
  2. NXstress writes it with a "calibration unknown" marker, not as the nominal chain.
  3. Every case records "unknown", and the file still loads. A failure to read the record is never a
    refused load (refusing shuts down GUI options); it is a warning, and the record is marked unknown so that
    NXstress writes the marker, not the nominal chain:
    • (a) and (b): warn, naming the file and the recorded error, and record "unknown".

    • (c): split the single except Exception into separate blocks, so that the log tells a damaged or
      unexpected file apart from a bug in PyRS:

      • the errors the record readers raise for a bad file: OSError (HDF5 read), KeyError (missing
        dataset or key), ValueError (including json.JSONDecodeError, and calibration_from_dict's refusal
        of a missing Lambda), RuntimeError (read_reduction_instrument: no geometry stored;
        calibration_from_dict: missing Status) → a warning that the file's calibration record could not be
        read;
      • any other Exception → logged as an error, with the traceback (logger.exception), saying it is
        probably a PyRS bug and should be reported.

      Both record "unknown" and let the load continue. The split is best-effort: a bug can also raise
      KeyError or ValueError, so the "bad file" warning keeps the exception type and message as today.

Current behaviour, for reference: in all three cases the project file loads normally (reduced data, logs,
masks, wavelength, geometry) and only the record is lost. A load never sets the detector shift, so the
workspace has neither shift nor record, and NXstress writes the nominal chain with calibrated=False. Only
(c) leaves a trace, as one warning line in the log.

Evidence:

  • workspaces.py, _read_recorded_calibration:
    if record.get("source", "none") == "none" or "calibration" not in record: return None.
  • file_object.py: when the record cannot be built, {"source": "unknown", "error": message}.
  • The agent's run through the real method: unknown+error -> None, json, no calibration key -> None,
    AttributeError (bug) -> None. Only the last one warned.

G3 — How calibration errors are carried — valid; one question for the author, one open question

Comment (agents):

  • Unknown errors are written as −1, which the calibration-file convention (calibration_nexus.py, and the
    project file's codes attribute) defines as "not refined (or held)". So
    a refined calibration whose errors were lost reads as "held". −2 means "refined but undetermined".
  • With several workspaces, the errors come from wss[0] only. When the shifts agree but the errors differ,
    the first workspace's errors win silently. The agent's run: same shift, errors 0.03 vs 9.0 -> 0.03.
  • _shift_values (append) ignores the errors when comparing.
  • If only some <name>_errors fields are present, shiftErrorFromNexus returns None without a warning,
    and the next write turns all seven into −1.

Reviewer:

  • Wherever the code "uses the first workspace", the fallback is useless. In general the right response to
    inconsistent inputs is to warn, and mark the values as inconsistent; whether to refuse is decided case
    by case, because refusing shuts down GUI options.
  • For example: differing errors for the same shift indicate a different calibration, a case that probably should be
    refused.

Resolution: valid. #1132 takes the first input's errors, with no check and no warning, in two places:

  1. _Instrument.init_group: shift_error = cls._applied_shift(wss[0])[1]. A multi-workspace write keeps the
    first workspace's errors.
  2. _Instrument.validateAppend: compares geometry and shift with what is on disk, but never reads the
    on-disk errors (shiftErrorFromNexus is not called). An append whose errors differ is accepted, and the
    entry keeps the first write's errors.

In PyRS core, append_hidra_project compares with _shift_values, which also ignores the errors: same shift,
different errors keeps the first file's errors, with no warning.

The errors come out of the same refinement as the values, so they are part of the calibration. Seven
bit-identical values with different errors are either two refinements or a sign that something went wrong
(values copied, a parameter held in one run and refined in the other, a hand-edited file). Neither can be
told apart from the data, so it is treated as a different calibration.

Suggestion, case by case:

  • Both inputs carry errors, and they differ: refuse, exactly as for a differing shift (R2). NXstress
    refuses in _entry_wide_geometry and validateAppend; a PyRS-core merge records the calibration as
    CalibrationSource.UNKNOWN, as R2 does for differing shifts. G1's
    content hash covers the values and the errors, so one key comparison detects it.
  • One input's errors are missing (lost on some path): see the open question below. Until it is answered,
    the working rule is: do not refuse; warn, and keep the errors that are known. They are not "the first
    input's" errors but the only ones there are.
  • A partial _errors set read back from NXstress: warn and mark the errors inconsistent, rather than
    reading them as "no errors" and writing −1 on the next save. Not a refusal: the file must still load.
  • Question for the author, revisiting a recorded decision: #1132's ground truth records "−1 where none are
    known" as a user decision, and it is the convention read_calibration_nexus already uses (#1098). So
    this is not a bug. The reason to revisit it: G2's "unknown" and G3's "errors inconsistent" are new states,
    and −1 ("not refined (or held)") would label a refined calibration as held in both. Should a calibrated
    entry whose errors are unknown or inconsistent use −2 ("refined but undetermined"), or a distinct code?

OPEN QUESTION — is a calibration without errors a different calibration? The reviewer's view: it
probably should be. If so, values-without-errors and the same values-with-errors are refused like any
other differing calibration, and the content hash simply includes the "errors unknown" state. If not, two
records match on the values, and on the errors only when both carry them, which the hash comparison has to
special-case. The answer also decides how often a save is refused in practice: today, several paths lose
the errors (_applied_shift returns no errors whenever the workspace's shift does not match its record,
and a partial _errors set reads back as none).

Not affected: the masks also come from wss[0], but _validate_masks_agree checks every input first
(pre-existing). instrumentFromNexus's local first(*names) is the first field name present, not the
first workspace; see G9 (1).

G4 — Tests for the recorded-calibration path — valid, important

Comment: every append test builds its workspace with make_minimal_HidraWorkspace(with_instrument=True),
which calls set_detector_shift. So no test reaches _applied_shift's recorded-only branch, which is the
normal case for a workspace loaded from a project file, through a multi-workspace write or an append. The
write-time refusal "input workspaces disagree on detector shift" has never been tested (that part predates
#1132). If _entry_wide_geometry reverted to get_detector_shift(), only the two single-workspace tests
below would fail; no multi-workspace write or append test would (checked by patching it: 2 failed, 118 passed, 2 xfailed).

Checked: the recorded-only branch is covered for a single workspace:
test_instrument.py::test_errors_are_the_recorded_calibrations (shift None, record set) and
test_errors_survive_a_read_back_and_rewrite. The gap is the multi-workspace write and the append, where the
shifts are compared.

Resolution: valid. Suggested unit tests, named by the agent:

  • test_differing_recorded_calibrations_are_refused (parametrized "other" / "none");
  • test_shared_recorded_calibration_merges;
  • test_append_of_recorded_calibration_only (parametrized "same" / "other").

These three stay valid whatever G1–G3 decide: R2 keeps the refusal of differing shifts.

Tests that G1–G3 will change. Under G1, every test whose workspace carries only a detector shift (the
make_minimal_HidraWorkspace(with_instrument=True) default) must also set the record: a trial patch of
_applied_shift to read only the record fails 8 NXstress unit tests (in test_instrument.py, test_append.py
and test_workspace_read.py). Two of them pin behaviour that is meant to change. Whoever implements G1 or G3
should expect to rewrite them, not treat their failure as a regression:

  • test_own_shift_wins_over_another_record pins _applied_shift's preference for the workspace's shift over
    the record. G1 removes that preference: NXstress reads only the record.
  • test_errors_unknown_are_not_refined pins −1 for lost errors. It depends on G3's question to the author
    (−1 or −2) and on G3's open question.

Tests that come with G1–G3. Each change brings its own tests, written by the PR (or commit) that implements it, not
by this review:

  • G1: reduction sets the record (None for nominal); the content key; a reload restores the record.
  • G2: each failure case records "unknown"; NXstress writes the "calibration unknown" marker; the bad-file and
    PyRS-bug cases log differently.
  • G3: differing known errors are refused; missing errors as G3's open question decides (the working rule:
    warn and keep the known ones); a partial _errors set warns and is marked inconsistent.

Minor: test_arm_angles_and_length_are_the_runs has a dead if l2 is None else l2 branch. HB2B_3510 has
no L2 log, so the test could assert that directly.

Evidence:

  • grep -rn "disagree on" tests matches only test_sample.py's stress-direction refusal.
  • The agent's run: 0.3 0.4 refused, 0.3 None refused, 0.3 0.3 accepted. The behaviour is correct
    today; nothing pins it.

G5 — Factual errors in the documentation, and in a note written into files — valid, critical (docs)

Comment:

  • PowderPatternCalculator does not exist (workspaces.py __init__ comment; ground_truths.md). The
    class is ReductionApp.

  • ground_truths.md says the old chain was "the reverse of DetectorModel.lab_positions". It was not:

    • the rotation sub-order (Rz, Ry, Rx) matched;
    • 2θ₀ came first instead of last;
    • the translations came after the rotations instead of x/y before them.

    This was checked against CALIBRATION_TRANSFORMATIONS: shift_x, shift_y, rotation_z, rotation_y,
    rotation_x, arm_length, shift_z, two_theta_0, arm_rotation.

  • detector_transformations now writes the arm_rotation note "-(DAS arm 2theta), per sub-run" into
    calibration files too, where the value is 0 by rule. The old wording, "set per sub-run to …", was true for
    both kinds of file. Suggestion: one note per caller.

Resolution: valid. Ground truths are what later work relies on, so the first two should be fixed in this PR.
The note is smaller, but it is written into data files: every calibration file saved with #1132 carries a note
describing a value it does not hold (the reader refuses a non-zero arm_rotation there). A fix to the code
does not reach files already written, so it should be fixed before #1132 merges.

G6 — Comments left stale by the change — valid, suggestion

  • _instrument.py still says wavelength is the only field an append grows: the appendableDatasets
    docstring ("just the wavelength"), two validateAppend comments, and the init_group append branch ("the
    one per-scan-point field"). #1132 makes arm_rotation grow too. #1132 should fix these, since its change
    made them stale; the same lines are on the phase-3 branch, so R1's follow-up 2 becomes a check after the merge.
  • _entry_wide_geometry's docstring does not mention the L2 geometry or the applied shift, and promises a
    "calibration state" it does not return. Once G3 is done, the corrected docstring should also name the
    errors among what the inputs must agree on.
  • _applied_shift's docstring says a read-back shift has "no known errors"; the code gives it the recorded
    errors. G1 removes this fallback, so the docstring is worth fixing only if G1 is postponed.
  • The "written before #1099" hint in validateAppend. It is added only when the entry on disk has no
    arm_rotation, i.e. was written before #1099, not to every mismatch. But even then the mismatch may be a
    genuinely different calibration, so the hint should not name the entry's age as the cause. Suggested
    wording: "may be why; if so, write a new entry".
  • _shift_values and the append comment do not say that the errors are ignored: covered by G3, which
    makes the errors part of the comparison.
  • Smaller points:
    • transformation_chain still calls NXstress output future work: "(and, later, NXstress output)".
    • detector_transformations changes the attributes of the field it is given, undocumented.
    • _written_order, test_the_rotation_links_are_written_in_xyz_order and TestDetectorRotationOrder's
      "leaves both of them green" describe the old write order.
    • Explain why appendableDatasets checks datasets and.

G7 — Project rules — valid, important

Type hints and docstrings are CLAUDE.md rules. The others are, for now, only in CLAUDE.local.md, and each
is marked "(see Recommended coding rules, above)".

  • Keyword-only arguments (see Recommended coding rules, above): detector_transformations(shifts, shifts_error, arm_length, arm_rotation=None) has four arguments, one with a default, and both callers (calibration_nexus.py,
    _Instrument.init_group) pass them by position. The first two are both Optional[DENEXDetectorShift], so
    swapping the shift and its errors raises nothing, in Python or in mypy. Also,
    shift if is_calibrated else None is just shift: is_calibrated is shift is not None.

  • Type hints and Google docstrings (CLAUDE.md), on the new methods:

    • no annotation at all on _shift_values, _read_recorded_calibration and get_recorded_calibration. mypy
      skips the body of an unannotated function (its own annotation-unchecked note), so these are not checked;
    • set_recorded_calibration (-> None) and shiftErrorFromNexus (-> DENEXDetectorShift | None) are
      partly annotated: their bodies are checked, but their arguments are Any.

    So the (shift, shift_error) contract NXstress depends on, read through get_recorded_calibration, is
    never checked.

  • set_recorded_calibration(shift, shift_error=None) ("count the fillers", from the None rule; see
    Recommended coding rules, above): all five callers (one in production, the NXstress read-back, and four tests) pass the errors argument, so the default only lets a future caller drop them unnoticed;
    and set_recorded_calibration(None, err) silently discards err.

  • A record type is the vehicle for G1–G3. The agents offered a small frozen AppliedCalibration(shift, shift_error) in place of the bare tuple as the author's option. After G1–G3 it is no longer optional: the
    record must carry its source as a CalibrationSource literal (R2), including UNKNOWN with its reason (G2), a content key (G1), and an error state
    (known, lost, inconsistent; G3), while None means only "nominal detector". A bare (shift, error) tuple
    cannot express that. A typed record type also settles the two items above. The tuple fixes (type hints, no
    default) apply only if G1–G3 are postponed.

  • Function-local imports with no justification (see Recommended coding rules, above): #1132 adds five
    in tests/unit/pyrs/core/test_workspaces.py, in two test functions and the helper _calibrated_instrument.
    The h5py and HidraProjectFileMode imports in an earlier test predate #1132.

  • A test imports another test module's private helper (see Recommended coding rules, above): test_nxstress_calibration.py
    imports _chain_matrix from test_instrument.py. The rule's test exception covers only a test importing
    from the module it tests. Move it to tests/util/.

G8 — Simplifications — one important; the rest suggestions

All behaviour-preserving. G1–G3 decide which are still worth asking for.

Worth doing whatever G1–G3 decide:

  • Important: shiftErrorFromNexus types the seven names out again. The writer,
    detector_transformations, builds the <name>_errors fields from CALIBRATION_TRANSFORMATIONS; the reader
    has its own tuple. A rename in the table makes every read return None silently, which reads as "an entry
    written before #1099", i.e. the lost-errors case G3 says must warn. Take the names from the table, as
    read_calibration_nexus does, and build DENEXDetectorShift by keyword: the table is in chain order, not
    constructor order, so positional *values would misassign shift_z and all three rotations.
  • validateAppend's "written before #1099" hint is built inline in the message, inside the loop.
    Compute it before the loop; do it together with G6's rewording of that hint.
  • _effective_geometry. The L2 set comprehension wraps a generator; build it in two steps. The bare
    False in DENEXDetectorGeometry(rows, columns, pixel_x, pixel_y, l2.pop(), False) is the calibrated
    flag of R3
    , which the class discards today. Under the suggested DD-35 (keep the flag, refuse a second
    shift) it would start to matter, and would mark this geometry uncalibrated. Pass it by keyword,
    calibrated=False, so it is visible, and whoever implements DD-35 should check this call.
  • _load_recorded_calibration is one assignment. Keeping it to mirror _load_wave_length is fair; if
    kept, its docstring belongs on _read_recorded_calibration.

Overtaken by G1–G3; only if those are postponed:

  • The inner if in append_hidra_project is always true. G1 and G3 rewrite that block.
  • Two "same calibration" keys, _shift_values and _shift_key (detector_model.from_shift already
    gives the vector). G1's content key replaces both.
  • _applied_shift rebuilds a tuple it already has. G1 removes the fallback, and with it the method.

Covered elsewhere: keyword-only arguments for detector_transformations in G7; the
appendableDatasets docstring and its datasets and coupling in G6.

G9 — Pre-existing or minor

Reviewer: fields missing from a file raise two distinct concerns. (1) The NXstress backend should not read missing fields as zero.
(2) In PyRS core (e.g. the HidraProjectFile reader), the question is whether we can, or should, change
existing behaviour much.

(1) NXstress: missing fields are read as 0.0 — valid, important. Pre-existing; #1132 kept it and
extended it to the new names. In _Instrument.instrumentFromNexus, the local first(*names) returns 0.0
when none of its names is in the file:

  • no arm_length (or pre-#1099 distance): 0.0 reaches DENEXDetectorGeometry, which refuses it
    (ValueError: "Arm length" value=0.0 ... below minimum), so the read fails with a message that does not name
    the missing field;
  • calibrated=True and a shift field missing: that parameter becomes 0.0, an invented calibration value.

Nothing is logged. NXstress always writes every field, so a missing one means a truncated, damaged or foreign
file. Raising would refuse the load, which the warn-and-mark rule (G3) avoids where it can. Suggestion:

  • a missing calibration field: warn, and record the calibration as unknown (G2's state);
  • a missing arm length: warn, and store NaN, as #1132 already does for a missing arm angle (below), instead
    of today's refused read. A viewer reading strains does not need it, any later computation with it fails
    visibly, and the constructor accepts NaN.

If #1132 does not fix it, record it as DD-36. DD-35 (R3) and DD-36 collide with neither branch: phase 3
uses up to DD-33, #1132 up to DD-34.

(2) PyRS core: its own zero-default, and existing behaviour stays — no change proposed.

  • calibration_file_io.check_calibration_dictionary, which calibration_from_dict calls after its wavelength
    check, sets a missing
    Shift_*/Rot_*/TTH_0 to 0 with error −1, and a missing error to −1 (its docstring: "Missing
    parameters are set to 0 with an error of -1"). calibration_from_dict({'Lambda': 1.5, 'Status': 3, 'Shift_x': 0.01}) returns a shift with every other parameter 0.0 and every error −1, without a warning.
  • calibration_from_dict refuses a missing or unusable Lambda (ValueError), conflicting TTH_0 and
    two_theta_0 (ValueError) or a missing Status (RuntimeError), but no missing shift parameter.
  • HidraProjectFile.read_instrument_geometry reads detector_group["L2"] directly: a missing L2 is a
    KeyError.

This zero-default is long-standing core behaviour: changing it would change results for every existing
calibration file read through it, so it is not asked of #1132. At most it is worth a deferred defect of its
own, if the PR's author agrees it is one. The proposals in this review
that touch core (G1–G3, R2) change code #1132 itself adds (_read_recorded_calibration's handling of those
exceptions: G2's separate catch blocks and "unknown"; append_hidra_project's calibration merge), plus
pre-existing core code: one new step in ReductionApp.reduce_data, setting the record (G1); the content key in
the project file's record (G1); and CalibrationSource in HidraSetup and HidraProjectFile, including how a
file with no record loads (R2). None of these changes a reduced value. Each is still a production change needing the PR author's approval.

A missing 2theta log is written as NaN, silently — suggestion. Caused by #1132. The NaN is
honest and pinned by test_missing_arm_angle_is_nan, but nothing is logged, and _concatenated_arm_rotation's
except RuntimeError would also swallow any other RuntimeError from get_detector_2theta: the same
problem as G2's broad except. Suggested Fix: check for the log by name, warn once per workspace, and catch
nothing.

L2 values are compared for exact equality — no action. A difference refuses the write: a refusal
where the detector really is placed differently, like a differing shift, so consistent with G3's case-by-case
rule. No float noise has been seen; revisit only if it is.

R5 — Grounding the detector chain: the sample chain is cited, the detector chain is not

Reviewer: the sample and detector chains are analogous, and both bear on calibration. The sample chain's
rotation order was reconstructed by a probe from a cited reference; the detector chain should be grounded the
same way, in a citation, rather than in "what the code's authors specified as correct".

What the two chains share:

  • Both are NXtransformations chains placing something in the lab frame: SAMPLE_DESCRIPTION/transformations
    and DETECTOR/transformations.
  • Both can fail in the same ways: axis directions and signs, composition order, and the entry point.
    Implementing the 04 nxstress-internal-cleanup subspec for the NXstress hookup found the detector chain's
    entry point wrong (1 of 8 links reachable; decision 26 in that plan's decisions log); the sample chain
    was written to avoid the same defect.
  • Both mix constant parameters with per-scan-point values. The sample chain has a constant frame_offset and
    per-point vx/vy/vz, omega/chi/phi. The detector chain has the calibration (shifts, rotations, 2θ₀) and a
    per-point arm_rotation.
  • Both feed calibration-dependent results. The detector chain is the calibration; the sample chain fixes the
    sample side of the scattering geometry, on which pole figures depend.

How each is grounded:

Sample chain Detector chain
Referent PoleFigureCalculator.rotate_project_q, which implements Bob He, Two-Dimensional X-ray Diffraction, ch. 8.3 (cited in its docstring and in _sample.py) DetectorModel.lab_positions / detector_model.rotation_matrix: code, no citation
How it was established We probed the formula, driven as a black box, for its matrix; of 2880 candidate compositions exactly one survives, M0 @ R_omega(0,-1,0) @ R_chi(1,0,0) @ R_phi(0,0,-1), worst error 5.8e-14 Decision 26: only the rotation sub-order (Rx @ Ry @ Rz) was compared with reduce_hb2b_pyrs.generate_rotation_matrix (since removed, #1011; replaced by detector_model.rotation_matrix). #1132: the whole chain against lab_positions, to 1e-12 m
Pinned by test_sample.py::TestSampleTransformationChain::test_the_rotations_compose_in_write_order, against rotate_project_q itself test_instrument.py, against lab_positions
Status Landed with the 04 internal-cleanup work (i.e. 'phase 2'); #1132 does not touch it #1132

What this shows:

  1. A check against code is only as good as the code, and only as wide as the check. Decision 26 concluded
    "the written order was already correct" from the rotation sub-order alone. #1132 resolved the 2θ₀ axis
    (about X, already flagged as open in the old writer) and found the rest of the old chain wrong: 2θ₀ applied
    first, the translations after the rotations. #1132's own test proves
    that NXstress places pixels where reduction does, not that reduction is right.
  2. Nothing checks that the two chains share one lab frame. The detector side states +Z along the beam,
    +Y up (calibration_nexus.py). The sample side needs a constant 180° frame_offset about +x to map ch. 8.3's
    output frame onto PyRS's, and the 04 work left open whether that offset is physical or an artefact of the
    convention. Each chain is tested alone, so a sign disagreement between them passes every test.

Suggestion:

  • Ground the detector chain in an external referent, the way the sample chain is, with a probe and a test
    against that referent. Candidates, none yet checked:
    • He's book, which may also treat the geometry of a 2D detector (a lead; the chapter is not identified);
    • Mantid's HB2B instrument definition, which reduction through Mantid uses.
  • Add one test that composes both chains in the same lab frame, e.g. the scattering vector of a pixel
    computed from the written sample and detector chains, against rotate_project_q's convention.
  • Neither change is a defect in #1132. Both are follow-up work; the timing is the PR author's call.
  • Ours, after this review (not asked of #1132): correct decision 26's conclusion in our plan records for the
    04 work, pointing here and at #1132's ground truth.

Evidence:

  • grep -rn "Bob He" pyrs → polefigurecalculator.py (rotate_project_q docstring) and _sample.py only.
  • detector_model.py and reduce_hb2b_pyrs.py: no citation for the rotation convention.
  • git diff 9fd090e2...19dd2525 --stat: neither _sample.py nor test_sample.py is changed.

…-compat, missing fields refused

Addresses parts of the #1132 review (G5, G6, G9) with user-approved changes:

- Calibration NeXus file: the transformation chain ends at two_theta_0 and
  holds no arm_rotation. The file stores the calibration parameters only;
  PyRS builds the instrument from them and each sub-run's arm angle. The
  reader checks shift_x..two_theta_0 and skips an arm_rotation entry.
  detector_transformations takes arm_rotation as a required keyword; the
  arm_rotation note is written only by NXstress, where it is true.
- No backward compatibility for NXstress or calibration NeXus files:
  removed the pre-#1099 old-name fallbacks, the before_1099 append hint and
  the arm_rotation presence guards. An append needs both per-scan-point
  fields (_Instrument._APPENDED) and is refused naming a missing one.
- instrumentFromNexus refuses a missing field (pixel layout, calibrated
  flag, arm_length, calibration values, wavelength) with a RuntimeError
  naming it, instead of reading 0.0 or defaulting to uncalibrated.
- Docs (G5/G6): ReductionApp, not PowderPatternCalculator; the old chain's
  real differences from lab_positions; stale comments on what an append
  grows, _entry_wide_geometry, _applied_shift and the rotation-order tests.

No reduced value changes. Follow-ups: #1140, #1141 (calibration hash,
nominal calibration), #1142 (errors required in calibration files).

Refs #1099, #1132

Assisted-by: Claude Code
… errors, test helpers

- detector_transformations(shifts, *, shifts_error, arm_length, arm_rotation):
  the shift and its errors (both Optional[DENEXDetectorShift]) can no
  longer be swapped by position; both callers pass them by name.
  `shift if is_calibrated else None` is just `shift`.
- HidraWorkspace.set_recorded_calibration: shift_error is required; every
  caller passed it, and the default only let one drop it unnoticed.
- Tests: the #1132 function-local imports in test_workspaces.py move to the
  top; chain_matrix and rodrigues move to tests/util/transformation_helpers.py
  as public helpers, so the integration test no longer imports a private
  name from another test module.

Type hints on the (shift, errors) tuple are left to #1141, whose record type
replaces it and which merges before this PR. No computed value changes.

Refs #1099, #1132

Assisted-by: Claude Code
…ing errors refused

- shiftErrorFromNexus takes the parameter names from
  CALIBRATION_TRANSFORMATIONS (the writer's table) instead of its own copy,
  and builds the shift by keyword through the new public
  calibration_nexus.shift_from_parameters (shared with the calibration file
  reader). A missing <name>_errors is refused by name: NXstress always
  writes all of them, so one missing is a failed write or a corrupt file.
- _effective_geometry: L2 values gathered in two steps; the calibrated flag
  passed by keyword (calibrated=False), for DD-35 (#1143).
- append_hidra_project: drop an inner `if` that was always true.
- _applied_shift: return the recorded tuple instead of rebuilding it.
- Ground truths: the "-1 where no errors are known" decision is superseded
  (-1 default, -2 unknown), to be implemented by #1141.

No computed value changes; a corrupt NXstress file is refused.
Blocked by #1141, #1142, #1143 (must merge first).

Refs #1099, #1132

Assisted-by: Claude Code
…corded-calibration tests

- NXstress refuses a workspace without a 2theta log (RuntimeError naming the
  workspace): without the arm angle the detector cannot be placed (user
  decision, G9). It used to write NaN, and its `except RuntimeError` could
  hide other errors; the log is now checked by name and nothing is caught.
- make_minimal_HidraWorkspace sets a 2theta log by default, as real data
  has (with_arm_angle=False to omit it).
- G4: TestRecordedCalibrationAcrossWorkspaces covers workspaces that carry
  only a recorded calibration (as loaded from a project file): differing
  records (another calibration, or none) are refused in a multi-workspace
  write; a shared one merges with its errors; an append with the same
  record grows the entry, with another is refused. Four of the five fail if
  _applied_shift ignores the recorded calibration.
- test_arm_angles_and_length_are_the_runs: dead L2 branch removed;
  HB2B_3510 has no L2 log, which the test now asserts.
- Ground truths: arm angle required; calibration defaults (0, error -1) and
  L2 as part of the calibration hash (#1141).

No computed value changes for data with a 2theta log.

Refs #1099, #1132

Assisted-by: Claude Code
fanchercm added a commit that referenced this pull request Nov 24, 2026
…ilot mirror

Adds five rules after "Code Quality Standards", proposed in the review of
#1132 and adopted by the maintainer:
- `None` must name a value, not a gap
- Keyword-only arguments
- Import placement
- Private names do not cross module boundaries
- Named states are literals, not free text

Adapted from the proposal: rule 5 has no UNKNOWN member, and a stored
string that is not a member is rejected, not mapped to a fallback (the
maintainer's decision for calibrations, #1141). Rule 4's NXstress file list
names only files on `next`. A review pass corrected factual claims (existing
functions already cross the keyword-only threshold; three deferred imports
in _peaks.py; one source default, in HidraSetup), "Three things", and the
examples' return type hints.

Adds .github/copilot-instructions.md, which CLAUDE.md has always named as
its mirror but which did not exist: the same text, with links relative to
.github/.

Refs #1132

Assisted-by: Claude Code
@fanchercm

fanchercm commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review. Below, each item is answered in the review's order (R1 → R5, with G1–G9 under R4), then the recommended coding rules. Each production change was approved individually by the maintainer.

Outcome: what fits #1132 is done on this branch, e81ba456..731b728e, which also merges the current next. The calibration redesign moves to #1140–#1143, which merge before this PR.


R1 — Merge order

Decision: #1140, #1141, #1142 and #1143 merge first, then #1132, then NXstress phase 3. #1099 is marked blocked by all four.

This replaces the proposal that #1132 go ahead of phase 3 on its own. The calibration work this review surfaced has to land first.

R2 — One NXstress entry holds one calibration

Decision: keep the refusal, and never record an "unknown" calibration.

  1. A single NXstress entry still refuses inputs with different calibrations. This is unchanged in NXstress writes the calibration file's detector chain (#1099) #1132.
  2. A PyRS-core merge of different calibrations (append_hidra_project, CombineRuns) is rejected, not recorded as unknown → Calibration identity: combine data only when calibration hashes match; one wavelength per NXstress entry #1140.
  3. Uncalibrated means the nominal calibration: parameters 0, errors −1, and the MonoSetting wavelength. Anything that cannot be stated is rejected → Calibration content hash: a calibration identifies itself and owns the "same calibration?" check #1141. That covers:
  4. CalibrationSource stays, with none/file/workspace and no UNKNOWN member. A stored string that is not a member is rejected → Calibration content hash: a calibration identifies itself and owns the "same calibration?" check #1141.

R3 — Can a detector shift be applied more than once?

Decision: fix it before this PR, rather than deferring it.

Your DD-35 is #1143, the discarded calibrated flag and apply_shift, and it blocks #1099. #1132 now passes calibrated=False by keyword in _effective_geometry, so that fix can find it.

R4 — General review

Item Outcome Where
G1 (several holders, no identity, reduction doesn't record) One record on the workspace, written by reduction every time. A content hash computed by the calibration itself covers the shift, 2θ₀, wavelength and L2, and every "same calibration?" check goes through it. A nominal calibration replaces None. #1141
G2 (unknown written as uncalibrated) No "unknown" state; see R2. #1141
G3 (errors) −1 is the default, −2 an unknown error, and no input's errors win silently. Whether the errors are part of the hash is still open. A partial _errors set is now refused: in NXstress by this PR, in calibration files by #1142. #1141, #1142, this PR
G4 (recorded-calibration tests) TestRecordedCalibrationAcrossWorkspaces: refusals, merges and appends for workspaces that carry only a recorded calibration. Four of its five tests fail if _applied_shift ignores the record. The dead L2 branch is removed. this PR
G5 (factual errors) ReductionApp; the old chain's real differences from lab_positions. The arm_rotation note is solved by a format change: the calibration file no longer holds an arm angle. Its chain ends at two_theta_0, the reader skips an arm_rotation entry if present, and PyRS adds each sub-run's angle. this PR
G6 (stale comments) All fixed. The pre-#1099 hint went away with backward compatibility: neither NeXus format keeps old layouts, so the old-name fallbacks, the before_1099 hint and the presence guards are removed. this PR
G7 (project rules) detector_transformations(shifts, *, shifts_error, arm_length, arm_rotation); set_recorded_calibration requires shift_error; imports at the top; chain_matrix and rodrigues are public in tests/util/. Type hints for the (shift, errors) tuple come with #1141's record type. this PR, #1141
G8 (simplifications) shiftErrorFromNexus takes its names from CALIBRATION_TRANSFORMATIONS and builds the shift by keyword (shift_from_parameters); calibrated=False by keyword; the always-true if is removed; _applied_shift returns the recorded tuple. _load_recorded_calibration is left for #1141. this PR
G9 (missing fields, defaults, L2) A missing field is a corrupt file: instrumentFromNexus and shiftErrorFromNexus refuse it by name, with no 0.0 or None substitutes. A missing 2theta log is refused; NaN is no longer written. Defaults are 0 with error −1, so the JSON reader stays as it is. L2 is compared through the calibration hash. this PR, #1141

R5 — Grounding the detector chain

Decision: the detector chain is a self-consistent choice. PyRS defines it in DetectorModel, the calibration refines its parameters in that model, and both file formats write exactly that chain. It needs no external reference; the check that matters is that the written chain places pixels where reduction does, which the tests confirm to 1e-12 m. This is recorded in the ground truths.

Recommended coding rules

All five are adopted in #1144 (merged), together with the .github/copilot-instructions.md mirror. Rule 5 is adapted: an unrecognised stored string is rejected rather than mapped to a fallback.


Also found: DD-36. A refused NXstress write can leave a partial file. GUI saves are protected; direct use of NXstress is not. It is recorded and deferred.

Coordination: #1140 reverses decision 18 of your plan (one wavelength per entry) and overlaps phase 3, so let's agree on it there.

🤖 Generated with Claude Code

fanchercm added a commit that referenced this pull request Nov 24, 2026
CLAUDE.md: adopt five coding rules from the #1132 review; add the Copilot mirror
- _Instrument._required: type hints and Google docstring.
- test_chain_with_wrong_link_is_refused: a transformation's depends_on is
  checked (nothing failed if that comparison were dropped).
- make_minimal_HidraWorkspace: the default 2theta log is derived from the
  sub-run numbers, so workspaces over different sub-runs differ and an
  ordering bug in a multi-workspace write or append shows.
- TestRecordedCalibrationAcrossWorkspaces: assert the arm angles' values,
  not only the array length.
- test_append_without_arm_angle_leaves_file_unchanged; a missing
  DETECTOR/transformations group is refused by name;
  test_instrumentFromNexus_standalone uses Arrange/Act/Assert.

Defects recorded, not fixed:
- DD-36: a refused NXstress write can leave a partial file (GUI saves are
  protected; direct NXstress use is not).

Refs #1099, #1132

Assisted-by: Claude Code
…-chain

# Conflicts:
#	docs/deferred_defects.md
#	docs/ground_truths.md
@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.46154% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.18%. Comparing base (82a9eba) to head (731b728).

Files with missing lines Patch % Lines
pyrs/core/workspaces.py 96.15% 1 Missing ⚠️
pyrs/utilities/NXstress/_instrument.py 98.59% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             next    #1132      +/-   ##
==========================================
+ Coverage   87.12%   87.18%   +0.06%     
==========================================
  Files         106      106              
  Lines       16655    16702      +47     
==========================================
+ Hits        14510    14562      +52     
+ Misses       2145     2140       -5     
Flag Coverage Δ
gui 69.52% <81.53%> (+<0.01%) ⬆️
integration 57.61% <87.69%> (+0.10%) ⬆️
ring-calibration 32.47% <36.92%> (+0.06%) ⬆️
unit 56.41% <98.46%> (+0.61%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@fanchercm

Copy link
Copy Markdown
Collaborator Author

@ekapadi I've restructured my reply to your review so it goes through R1 → R5 in order, with G1–G9 under R4: #1132 (comment)

Since then the branch has merged the current next and is mergeable again. It also picked up the follow-ups from my own code and test reviews (1d12203a, including DD-36).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants